﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; 
using SHKF.B2C.BLL.Center;
using SHKF.B2C.MeiTuanShanGou.BLL;
using SHKF.B2C.MeiTuanShanGou.Model.Dto.Token;
using SHKF.B2C.MeiTuanShanGou.Model.Entity;
using SHKF.B2C.MeiTuanShanGou.Network;
using SHKF.B2C.Model;
using SHKF.B2C.Model.Dto;
using SHKF.B2C.Model.Entity.Center;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SHKF.B2C.MeiTuanShanGou.Token.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class TokenController : ControllerBase
    {  
        private readonly ShopMapBLL shopMapBLL;
        private readonly TokenMtsgBLL tokenMtsgBLL;
        private readonly HttpClientMeiTuanShanGou httpClientMeiTuanShanGou;

        public TokenController( 
            ShopMapBLL shopMapBLL,
            TokenMtsgBLL tokenMtsgBLL,
            HttpClientMeiTuanShanGou httpClientMeiTuanShanGou) 
        {
            
            this.shopMapBLL = shopMapBLL;
            this.tokenMtsgBLL = tokenMtsgBLL;
            this.httpClientMeiTuanShanGou = httpClientMeiTuanShanGou;
        }

        [HttpGet("refresh")]
        public async Task<TokenMeiTuanDto> Refresh(int ShopSN)
        {
            TokenMeiTuanDto dto = new TokenMeiTuanDto();

            DateTime now = DateTime.Now;
            long timestamp = DateTimeUtil.DateTimeToTimeStamp(now.AddHours(1)); //一小时误差

            ShopMapEntity shopCEntity = this.shopMapBLL.Get(ShopSN, PlatformEnum.Mtsg);
            if (shopCEntity == null || shopCEntity.app_poi_code == 0)
            {
                dto.error = new Error() { code = -1, msg = $"门铺:{ShopSN}的 app_poi_code不能为空" };
                return dto;
            }
            long app_poi_code = shopCEntity.app_poi_code;

            TokenMeiTuanEntity requestToken = this.tokenMtsgBLL.Get(app_poi_code);

            this.httpClientMeiTuanShanGou.app_poi_code = app_poi_code;

            //如果数据中没有从接口中获取 
            if (requestToken == null || string.IsNullOrEmpty(requestToken.access_token))
            {
                dto = await this.httpClientMeiTuanShanGou.GetToken(timestamp);
                if (dto != null && !string.IsNullOrEmpty(dto.access_token))
                {
                    SaveTokenToDB(app_poi_code, dto);
                }
                else if (dto.status != 0)
                {
                    return dto;
                }
            }
            else
            {
                dto.access_token = requestToken.access_token;
                dto.refresh_token = requestToken.refresh_token;
                dto.expires_in = requestToken.expires;
                dto.re_expires_in = requestToken.refresh_expires;
                dto.status = 0;
                dto.state = "";
                dto.message = "";

                this.setHttpToken(dto.access_token);


                //强制刷新    
                if (requestToken.refresh_expires <= timestamp) //如果刷新时间也过期了,需要重新申请店铺，这是极端事件，需要手动去美团的平台操作
                {
                    // dto.message = "授权已经过期，请联系商家重新授权,这是长期不用导致,同时删除它家美团的token";
                    dto.error = new Error() { code = -1, msg = "授权已经过期，请联系商家重新授权,这是长期不用导致,同时删除它家美团的token" };
                }
                else //如果refresh_token没有过期，重新刷新
                {
                    long t = this.httpClientMeiTuanShanGou.GetTimeStamp();
                    dto = await this.httpClientMeiTuanShanGou.PostRefreshToken(requestToken.refresh_token, t);

                    //保存刷新的Token 
                    if(dto.status == 0)
                    {
                        SaveTokenToDB(app_poi_code, dto);
                    } 
                }
            }

            return dto;
        }

        [HttpGet("create")]
        public async Task<TokenMeiTuanDto> Create(int ShopSN)
        {
            TokenMeiTuanDto dto = new TokenMeiTuanDto();

            ShopMapEntity shopCEntity = this.shopMapBLL.Get(ShopSN, PlatformEnum.Mtsg);
            if (shopCEntity == null || shopCEntity.app_poi_code == 0)
            {
                dto.error = new Error() { code = -1, msg = $"门铺:{ShopSN}的 app_poi_code不能为空" };
                return dto;
            }
            long app_poi_code = shopCEntity.app_poi_code;

            this.httpClientMeiTuanShanGou.app_poi_code = app_poi_code;

            DateTime now = DateTime.Now;
            long timestamp = DateTimeUtil.DateTimeToTimeStamp(now.AddHours(1)); //一小时误差

            dto = await this.httpClientMeiTuanShanGou.GetToken(timestamp);
            if (dto != null && !string.IsNullOrEmpty(dto.access_token))
            {
                SaveTokenToDB(app_poi_code, dto);
            }
            else if (dto.status != 0)
            {
                return dto;
            }

            return dto;
        }

        private void SaveTokenToDB(long app_poi_code, TokenMeiTuanDto dto)
        {
            DateTime now = DateTime.Now;

            TokenMeiTuanEntity token = new TokenMeiTuanEntity();
            token.app_poi_code = app_poi_code;

            int day = (int)(dto.expires_in / 3600 / 24);
            int day_r = (int)(dto.re_expires_in / 3600 / 24);

            token.access_token = dto.access_token;
            token.expires = DateTimeUtil.DateTimeToTimeStamp(now.AddDays(day));

            token.refresh_token = dto.refresh_token;
            token.refresh_expires = DateTimeUtil.DateTimeToTimeStamp(now.AddDays(day_r));

            this.tokenMtsgBLL.Save(token);
             
        }
        private void setHttpToken(string access_token)
        {
            this.httpClientMeiTuanShanGou.access_token = access_token;
        }


    }
}
